package com.yc.helper;

import cn.dev33.satoken.context.SaHolder;
import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.ObjectUtil;
import com.yc.domain.LoginUserDto;
import com.yc.enums.DeviceEnum;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;

@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class LoginHelper {

    public static final String LOGIN_USER_KEY = "loginUser";

    /**
     * 登录系统
     *
     * @param loginUserDto 登录用户信息
     */
    public static void login(LoginUserDto loginUserDto) {
        SaHolder.getStorage().set(LOGIN_USER_KEY, loginUserDto);
        StpUtil.login(loginUserDto.getId());
        setLoginUser(loginUserDto);
    }

    /**
     * 注销
     */
    public static void logout() {
        StpUtil.logout();
    }

    /**
     * 获取当前token信息
     */
    public static SaTokenInfo getTokenInfo() {
        return StpUtil.getTokenInfo();
    }

    /**
     * 登录系统 基于 设备类型
     * 针对相同用户体系不同设备
     *
     * @param loginUserDto 登录用户信息
     */
    public static void loginByDevice(LoginUserDto loginUserDto, DeviceEnum deviceType) {
        SaHolder.getStorage().set(LOGIN_USER_KEY, loginUserDto);
        StpUtil.login(loginUserDto.getId(), deviceType.getValue());
        setLoginUser(loginUserDto);
    }

    /**
     * 设置用户数据(多级缓存)
     */
    public static void setLoginUser(LoginUserDto loginUserDto) {
        StpUtil.getTokenSession().set(LOGIN_USER_KEY, loginUserDto);
    }

    /**
     * 获取用户(多级缓存)
     */
    public static LoginUserDto getLoginUser() {
        LoginUserDto loginUserDto = (LoginUserDto) SaHolder.getStorage().get(LOGIN_USER_KEY);
        if (loginUserDto != null) {
            return loginUserDto;
        }
        loginUserDto = (LoginUserDto) StpUtil.getTokenSession().get(LOGIN_USER_KEY);
        SaHolder.getStorage().set(LOGIN_USER_KEY, loginUserDto);
        return loginUserDto;
    }

    public static boolean isLogin() {
        LoginUserDto loginUserDto = getLoginUser();
        if (loginUserDto != null) {
            return true;
        }
        return StpUtil.isLogin();
    }

    public static Long getUserId() {
        LoginUserDto loginUserDto = getLoginUser();
        if (ObjectUtil.isNull(loginUserDto)) {
            return StpUtil.getLoginIdAsLong();
        }
        return loginUserDto.getId();
    }

    public static String getUserIdStr() {
        return getUserId().toString();
    }

    /**
     * 获取用户账户
     */
    public static String getUsername() {
        return getLoginUser().getUsername();
    }

}
